package com.atguigu.spzx.pay.service;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.atguigu.common.utils.ThreadLocalUtil;
import com.atguigu.spzx.model.dto.product.SkuSaleDto;
import com.atguigu.spzx.model.entity.order.OrderInfo;
import com.atguigu.spzx.model.entity.order.OrderItem;
import com.atguigu.spzx.model.entity.pay.PaymentInfo;
import com.atguigu.spzx.order.feign.OrderServiceFeign;
import com.atguigu.spzx.pay.mapper.PaymentInfoMapper;
import com.atguigu.spzx.pay.properties.AlipayProperties;
import com.atguigu.spzx.product.feign.ProductServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    OrderServiceFeign orderServiceFeign;

    @Autowired
    PaymentInfoMapper paymentInfoMapper;

    @Autowired
    AlipayProperties alipayProperties;

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    ProductServiceFeign productServiceFeign;


    @Override
    public String alipay(String orderNo) {

        Long userId = ThreadLocalUtil.getUserInfo().getId();

        OrderInfo orderInfo = orderServiceFeign.getByOrderNo(orderNo);

        this.createPaymentInfo(userId, orderNo, orderInfo);


        String form = this.handleAlipayWapPay2(orderInfo);

        return form;
    }

    private String handleAlipayWapPay2(OrderInfo orderInfo) {
        //无论调用支付宝的那个接口，都是要使用到一个AlipayClient对象（单例即可）
//        AlipayClient alipayClient = new DefaultAlipayClient(
//                alipayProperties.getAlipay_url(),
//                alipayProperties.getApp_id(),
//                alipayProperties.getApp_private_key(),
//                AlipayProperties.format,//参数的格式json
//                AlipayProperties.charset,
//                alipayProperties.getAlipay_public_key(),
//                AlipayProperties.sign_type);//非对称的加密算法


        //对于支付端不同的接口，使用不同的request对象
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();


        //异步接收地址，仅支持http/https，公网可访问（当支付成功或失败时，该接口会被自动调用）
        request.setNotifyUrl(alipayProperties.getNotify_payment_url());

        //同步跳转地址，仅支持http/https （支付成功后，跳转的页面地址）
        request.setReturnUrl(alipayProperties.getReturn_payment_url());


        /******必传参数******/
        JSONObject bizContent = new JSONObject();
        //商户订单号，商家自定义，保持唯一性
        bizContent.put("out_trade_no",orderInfo.getOrderNo() );//每次去调用支付宝接口时，需要传递的一个具有唯一性支付编号（可以使用订单的编号）
        //支付金额，最小值0.01元
        bizContent.put("total_amount", orderInfo.getTotalAmount().doubleValue());
        //订单标题，不可使用特殊符号（随便写）
        bizContent.put("subject", "测试商品");//手机端支付时会显示
        //手机网站支付，固定写QUICK_WAP_WAY
        bizContent.put("product_code", "QUICK_WAP_WAY");


        request.setBizContent(bizContent.toString());//必传参数，是json字符串格式

        //发起一个post类型的请求，对支付宝接口进行调用
        AlipayTradeWapPayResponse response = null;
        try {
            response = alipayClient.pageExecute(request, "POST");
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }


        //支付宝返回的form表单字符串
        String pageRedirectionData = response.getBody();

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }


        return pageRedirectionData;
    }


    private void createPaymentInfo(Long userId, String orderNo, OrderInfo orderInfo) {

        PaymentInfo paymentInfo = paymentInfoMapper.getByOrderNo(orderNo);

        if (paymentInfo!= null){
            return ;
        }

        paymentInfo  = new PaymentInfo();
        paymentInfo.setUserId(userId);
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPayType(2);
        //paymentInfo.setOutTradeNo();
        paymentInfo.setAmount(orderInfo.getTotalAmount());

        String content = "";
        for (OrderItem orderItem : orderInfo.getOrderItemList()) {
            content += orderItem.getSkuName()+ " ";
        }
        paymentInfo.setContent(content);
        paymentInfo.setPaymentStatus(0);

        paymentInfoMapper.addPayMentInfo(paymentInfo);
    }

    @Override
    public void afterPaySuccess(Map<String, String> paramsMap) {
        String orderNo = paramsMap.get("out_trade_no");//曾经调用支付宝的第一个接口时，传递的订单编号
        orderServiceFeign.afterPaySuccess(orderNo,2);

        String trade_no = paramsMap.get("trade_no");//支付宝返回的交易流水号（凭证号）
        paymentInfoMapper.afterPaySuccess(trade_no,orderNo,paramsMap.toString());

        OrderInfo orderInfo = orderServiceFeign.getByOrderNo(orderNo);

        List<SkuSaleDto> saleDtoList = new ArrayList<>();
        for (OrderItem orderItem : orderInfo.getOrderItemList()) {

            Integer skuNum = orderItem.getSkuNum();
            Long skuId = orderItem.getSkuId();

            SkuSaleDto skuSaleDto = new SkuSaleDto();
            skuSaleDto.setSkuId(skuId);
            skuSaleDto.setNum(skuNum);

            saleDtoList.add(skuSaleDto);
        }
        productServiceFeign.updateSkuStockNumAndSaleNum(saleDtoList);

    }

    @Override
    public void cancelPayment(String orderNo) {
        PaymentInfo paymentInfo = paymentInfoMapper.getByOrderNo(orderNo);
        Integer paymentStatus = paymentInfo.getPaymentStatus();
        if (paymentStatus.intValue() ==1){
            this.refundMoney(orderNo,paymentInfo.getAmount().doubleValue());
            paymentInfoMapper.updatePayment(-1,new Date(),orderNo);
        }else {
            paymentInfoMapper.updatePayment(-2,null,orderNo);

        }
    }

    private void refundMoney(String orderNo,double money) {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);//订单的编号
        bizContent.put("refund_amount", money);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }
}
